#美国的国债政府税收收入差
from datetime import datetime
from utils.akcache import Cache
import akshare as ak
import pandas as pd
import matplotlib.pyplot as plt

ac = Cache()

# 读取国债数据到DataFrame
df_debt = pd.read_csv("data/origin/USA/DebtPenny_19930401_20250930.csv")
df_debt = df_debt[['日期', '国债总额']]
df_debt['日期'] = pd.to_datetime(df_debt['日期'])



# 读取税收数据到DataFrame
df_income = pd.read_csv("data/origin/USA/USGovtRevCollect_20041001_20250930.csv")

#统计df_income,只获取日期和净征收金额
df_income = df_income[['日期', '净征收金额']]
df_income['日期'] = pd.to_datetime(df_income['日期'])

#每日总和
df_income = df_income.groupby('日期').sum().reset_index()


#月度总和
# 先将日期设置为索引，按月汇总后重置索引，并将日期列修改为仅保留年月
df_debt_M = df_debt.set_index('日期').resample('ME').sum().reset_index()
df_debt_M['日期'] = pd.to_datetime(df_debt_M['日期'].dt.to_period('M').astype(str))

df_income_M = df_income.set_index('日期').resample('ME').sum().reset_index()
df_income_M['日期'] = pd.to_datetime(df_income_M['日期'].dt.to_period('M').astype(str))

#合并数据
df_merged = pd.merge(df_debt_M, df_income_M, on="日期", how="inner")

#计算国债政府税收收入差
df_merged["国债政府税收收入差"] = df_merged["国债总额"] - df_merged["净征收金额"]

#输出结果
df_merged.to_csv("data/temp/index_usa_debt_income_diff.csv", index=False, encoding='utf-8-sig')

plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.plot(df_merged["日期"], df_merged["国债政府税收收入差"], label='国债政府税收收入差')
plt.title("国债政府税收收入差")
plt.xlabel("日期")
plt.ylabel("国债政府税收收入差")
plt.legend()
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig("data/temp/index_usa_debt_income_diff.png", dpi=300, bbox_inches='tight')
plt.show()
